package com.jvup.common.utils;

import android.os.CountDownTimer;

import com.jvup.common.function.Function;

import java.util.concurrent.TimeUnit;

/**
 * 倒计时器构建器
 */
public class CountDownTimerBuilder {

    public static CustomCountDownTimer build(long millisInFuture, long countDownInterval, TimeUnit timeUnit){
        return build(timeUnit.toMillis(millisInFuture), timeUnit.toMillis(countDownInterval));
    }

    public static CustomCountDownTimer build(long millisInFuture, long countDownInterval){
        return new CustomCountDownTimer(millisInFuture, countDownInterval);
    }

    public static class CustomCountDownTimer extends CountDownTimer {

        private Function<Long,Long> tickCallBack;
        private Function<Long,Long> finishCallBack;

        private long countDownTime;

        public CustomCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.countDownTime = millisInFuture;
        }

        public CustomCountDownTimer addTickCallBack(Function<Long,Long> tickCallBack) {
            this.tickCallBack = this.tickCallBack == null ? tickCallBack : this.tickCallBack.andThen(tickCallBack);
            return this;
        }

        public CustomCountDownTimer addFinishCallBack(Function<Long,Long> finishCallBack){
            this.finishCallBack = this.finishCallBack == null ? finishCallBack : this.finishCallBack.andThen(finishCallBack);
            return this;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if(tickCallBack != null) {
                countDownTime = tickCallBack.apply(countDownTime);
            }
        }

        @Override
        public void onFinish() {
            if(finishCallBack != null) {
                finishCallBack.apply(countDownTime);
            }
        }
    }

}
